package com.assumejson.mybatis.factorybean;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 使用动态代理将接口包装秤代理类生成BeanDefinition
 *
 * @author Mr. Li
 * @version 1.0
 * @since 1.0 2021/12/8 13:40
 */

public class MyMapperFactoryBean implements FactoryBean {

	private Class interFaceClass;

	private SqlSession sqlSession;

	public MyMapperFactoryBean(Class interFaceClass) {
		this.interFaceClass = interFaceClass;
	}

	@Autowired
	public void setSqlSession(SqlSessionFactory sqlSessionFactory) {
		// Error creating bean with name 'userMapper': FactoryBean threw exception on object creation; nested exception is org.apache.ibatis.binding.BindingException: Type interface com.assumejson.mybatis.mapper.UserMapper is not known to the MapperRegistry.
		// 该错误是Mybatis 没有映射的关系
		sqlSessionFactory.getConfiguration().addMapper(interFaceClass);
		this.sqlSession = sqlSessionFactory.openSession();
	}


	@Override
	public Object getObject() {
		return sqlSession.getMapper(interFaceClass);
	}

	@Override
	public Class<?> getObjectType() {
		return interFaceClass;
	}
}
